package org.rbreznak.tronco.client;

import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.util.EventObject;

import javax.swing.JFrame;

public class Tronco extends JFrame implements ScreenListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7404926107072885863L;

	private Screen current;
	private final Screen root;
	
	/**
	 * Tronco
	 *
	 */
	public Tronco() {
		// remove the windows headers (minimize, window and close buttons)
		this.setUndecorated(true);
		// make the frame fullscreen
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		// set the mouse cursor (blank or a finger)
		Image cursorImage = Toolkit.getDefaultToolkit().getImage("img/default.png");
		Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImage, new Point(10, 2), "" );
		this.setCursor(blankCursor);
		
		// make the frame visable
		this.setVisible(true);
		
		KeyboardTestScreen sn0 = new KeyboardTestScreen();
		OpeningScreen sn1 = new OpeningScreen();
		LoginScreen sn2 = new LoginScreen();
		DummyScreen sn3 = new DummyScreen("Screen #3");

		root = sn0;
		sn0.addNode(sn1);
		sn1.addNode(sn2);
		sn2.addNode(sn3);
		
		setScreen(root);
	}

	/**
	 * 
	 * @param screen
	 */
	public void setScreen(Screen screen) {
		if(screen != null) {
			this.removeKeyListener(current);
			current = screen;
			this.addKeyListener(current);
			this.setContentPane(current);
			current.removeAllButOneScreenListener(this);
			this.validate();
		} else {
			
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public Screen getScreen() {
		return current;
	}
	
	/**
	 * 
	 */
	public void screenUpdate(EventObject event) {
		System.out.println(event.getSource().toString());
		
		if(event.getSource() != current) {
			return;
		}
		if(current != null) {
			if(current.getNext() == null) {
				reset(root);
				setScreen(root);
			} else {
				setScreen(current.getNext());
			}
		} else {
			reset(root);
		}
	}
	
	/**
	 * 
	 * @param node
	 */
	private void reset(Screen node) {
		if(node != null) {
			for(int i=0;i<node.nodes.size();i++){
				reset(node.nodes.get(i));
			}
			node.reset();
		}
	}
	
}
